package com.vilynn.learning.juc.forkjoin;

import com.alibaba.fastjson.JSON;
import com.vilynn.learning.juc.forkjoin.service.RemoteService;
import com.vilynn.learning.pojo.FunObject;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;

public class ForkJoinTest {


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        long start = System.currentTimeMillis();
        forkJoin2();
        serial();
        long end = System.currentTimeMillis();
        System.out.println("cos time : " + (end-start));

    }

    public static void serial(){
        final RemoteService remoteService = new RemoteService();

        List<FunObject> funObjects = remoteService.getList("");
        FunObject funObject = remoteService.get("");

        funObjects.add(funObject);
        System.out.println(JSON.toJSON(funObjects));
    }

    public static void forkJoin2() throws ExecutionException, InterruptedException {
        final RemoteService remoteService = new RemoteService();

        ForkJoinPool forkJoinPool = new ForkJoinPool(2);

        ForkJoinTask<FunObject> task1 = forkJoinPool.submit(() -> remoteService.get(""));

        ForkJoinTask<FunObject> fork = task1.fork();

        ForkJoinTask<List<FunObject>> task2 = forkJoinPool.submit(() -> remoteService.getList(""));

        List<FunObject> funObjects = task2.get();
        FunObject funObject = task1.get();

        funObjects.add(funObject);
        System.out.println(JSON.toJSON(funObjects));
    }

}
